<script setup>
import { Message, MessageBox } from 'element-ui';
import { merge, pick } from 'lodash-es';
import dayjs from 'dayjs';
import { useRequest } from '@/hooks/requestHooks.js';
import { addMonitor, removeMP, updateMonitor, getMonitorLists, getMonitorNums } from '@/api/index.js';
import { useConfirmModal } from '@/store/xmgl.js';
import { TableList } from '@/components/MainComponents.js';
import SearchEnterprise from '@/components/EnterpriseInfo/SearchEnterprise.vue';
import MonitorInfo from '@/views/zdgl/components/MonitorInfo.vue';
import MonitorContract from '@/views/zdgl/components/MonitorContract.vue';
import QueryForm from '@/components/QueryForm.vue';

const appContainer = ref(null);
const contBoxHeight = ref(null);
const confirmModalStore = useConfirmModal();
const queryParams = ref({
  projectName: '',
  projectCode: '',
  enterpriseCode: '',
  pageNum: 1,
  pageSize: 10,
  projectType: 'JC',
});
const addBasicInfoParams = ref({
  projectName: '',
  enterpriseCode: '',
  buildingCodes: [],
});
const open = ref(false);
const openTitle = ref('');
const activeName = ref('jcxx');
const mpciDisabled = ref(true);
const mpbiDisabled = ref(false);
const mpbiProjectCode = ref('');
const mpciSubmit = ref(false);
const mpciBuildingCode = ref(null);
const today = dayjs();
const list = ref([
  { name: '监测项目数：', flag: 'projectCount' },
  { name: '监测机构数：', flag: 'institutionCount' },
]);
const searchData = ref({
  projectCode: '',
  projectName: '',
});
const searchList = ref([
  {
    type: 'input',
    label: '项目编号',
    prop: 'projectCode',
    placeholder: '请输入项目编号',
  },
  {
    type: 'input',
    label: '项目名称',
    prop: 'projectName',
    placeholder: '请输入项目名称',
  },
]);
const [res2, , run2] = useRequest(getMonitorNums, {
  defaultParams: [],
  manual: true,
});
const [res, loading, run] = useRequest(getMonitorLists, {
  defaultParams: [],
  manual: true,
});
const [, , addMonitorRun] = useRequest(addMonitor, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    if (data.code === 200) {
      Message.success(openTitle.value + '成功');
      activeName.value = 'htxx';
      mpbiDisabled.value = true;
      mpciDisabled.value = false;
      mpbiProjectCode.value = data.data.projectCode;
      mpciBuildingCode.value = data.data.buildingLevelOneList;
      handleQuery();
    }
  },
  onError: rej => {
    if (rej.msg === '所选报告关联区域与其他项目重复不可保存') {
      confirmModalStore.setDisplayCM(true);
    }
  },
});
const [, , updateProjectRun] = useRequest(updateMonitor, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    if (data.code === 200) {
      Message.success(openTitle.value + '成功');
      mpciBuildingCode.value = data.data.buildingLevelOneList;
      cancel();
      handleQuery();
      // activeName.value = 'htxx';
      // mpbiDisabled.value = true;
      // mpciDisabled.value = false;
      // mpbiProjectCode.value = data?.rows?.projectCode;
    }
  },
});
const [, , removeProjectRun] = useRequest(removeMP, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    loading.value = false;
    handleQuery();
    Message.success('删除成功');
  },
});
const handleQuery = () => {
  run(merge(queryParams.value, searchData.value));
  run2({ projectType: 'JC', enterpriseCode: queryParams.value.enterpriseCode });
};
const checkedChange = val => {
  queryParams.value.enterpriseCode = val?.enterpriseCode;
  handleQuery();
};
const resetQuery = () => {
  searchData.value = {
    projectCode: '',
    projectName: '',
  };
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  handleQuery();
};
const detailsMp = row => {
  mpciDisabled.value = true;
  mpbiDisabled.value = true;
  open.value = true;
  openTitle.value = '详情';
  mpbiProjectCode.value = row.projectCode;
};
const editMp = row => {
  mpbiProjectCode.value = row.projectCode;
  confirmModalStore.setOpenTitle('编辑');
  openTitle.value = '编辑';
  mpciDisabled.value = false;
  open.value = true;
};
const deleteMp = row => {
  MessageBox.confirm('删除后不可找回，是否删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      loading.value = true;
      removeProjectRun({ projectCode: row.projectCode });
    })
    .catch(() => {});
};
const columObj = ref({
  index: true,
  columnData: [
    {
      text: true,
      prop: 'projectCode',
      label: '项目编号',
    },
    {
      text: true,
      prop: 'projectName',
      label: '项目名称',
    },
    {
      slotName: 'agreement',
      label: '合约起止时间',
    },
    {
      slotName: 'building',
      label: '监测机构',
    },
    {
      slotName: 'operation',
      label: '操作',
    },
  ],
});
const getList = e => {
  queryParams.value.pageNum = e.page;
  queryParams.value.pageSize = e.limit;
  handleQuery();
};
const handleAdd = () => {
  open.value = true;
  openTitle.value = '新增';
};
const selectReport = params => {
  addBasicInfoParams.value.buildingCodes = params.buildingCodes;
  addBasicInfoParams.value.projectName = params.projectName;
  addBasicInfoParams.value.projectCode = params.projectCode;
  addBasicInfoParams.value.enterpriseCode = queryParams.value.enterpriseCode;
};
const mpciUpload = () => {
  mpciSubmit.value = false;
  cancel();
  handleQuery();
};
const submitForm = () => {
  if (openTitle.value === '详情') {
  } else {
    if (activeName.value === 'jcxx') {
      if (addBasicInfoParams.value.projectName?.length > 0 && addBasicInfoParams.value.buildingCodes?.length > 0) {
        addBasicInfoParams.value.buildingCodes = Array.from(new Set(addBasicInfoParams.value.buildingCodes));
        if (openTitle.value === '新增')
          addMonitorRun(pick(addBasicInfoParams.value, ['projectName', 'enterpriseCode', 'buildingCodes']));
        if (openTitle.value === '编辑')
          updateProjectRun(merge(addBasicInfoParams.value, { projectCode: mpbiProjectCode.value }));
      } else {
        Message.error('请填写项目名称或选择关联区域');
        return false;
      }
    } else {
      if (mpciDisabled.value) {
        Message.error('请先填写基础信息');
        return false;
      } else {
        mpciSubmit.value = true;
        setTimeout(() => {
          mpciSubmit.value = false;
        }, 1000);
        // cancel();
        // handleQuery(queryParams.value);
      }
    }
  }
};
const cancel = () => {
  open.value = false;
  mpbiDisabled.value = false;
  mpciDisabled.value = true;
  activeName.value = 'jcxx';
  openTitle.value = '';
  mpbiProjectCode.value = '';
};
onMounted(() => {
  nextTick(() => {
    contBoxHeight.value = appContainer.value.clientHeight - 120 - 122;
  });
});
</script>
<template>
  <div class="app-container u-df-st u-h100" ref="appContainer">
    <div class="architecture-left u-base-fg u-h100 u-br20 u-border-bg">
      <SearchEnterprise @checkedChange="checkedChange" :isDefaultSelect="true" />
    </div>
    <div class="architecture-right u-h100" :v-loading="loading">
      <div class="u-base-fg u-mb20 u-pt20 u-pl20 u-pr20">
        <QueryForm
          :searchList="searchList"
          :searchData="searchData"
          @resetQuery="resetQuery"
          @handleQuery="handleQuery"
        />
      </div>
      <div class="contBox" :v-loading="loading">
        <div class="u-df-spb u-mb20">
          <div>
            <span class="u-fs16 u-primary u-pr10" v-for="item in list" :key="item.name">
              <!-- {{ item.name + '--' }} -->
              {{ item.name + (res2?.[item.flag] ?? '--') }}
            </span>
          </div>
          <el-button size="small" type="primary" plain @click="handleAdd">新增监测项目</el-button>
        </div>
        <TableList
          :tableData="res?.rows ?? []"
          :height="contBoxHeight"
          :columObj="columObj"
          :total="res?.total ?? 0"
          :pageObj="queryParams"
          @getList="getList"
        >
          <template v-slot:agreement="{ scope }">
            <span v-if="!scope.row.agreementStartTime && !scope.row.agreementEndTime">--</span>
            <span v-else>{{ scope.row.agreementStartTime ?? '--' }} - {{ scope.row?.agreementEndTime ?? '长期' }}</span>
          </template>
          <template v-slot:building="{ scope }">
            <!-- <span>{{ scope.row.buildingLevelOneList }}</span> -->
            <span v-for="item in scope.row.buildingLevelOneList" :key="item.buildingCode">
              {{ item.buildingViewId + '-' + item.buildingName + ',' }}
            </span>
          </template>
          <template v-slot:operation="{ scope }">
            <el-button size="mini" type="text" @click="detailsMp(scope.row, scope.$index)">详情</el-button>
            <el-button size="mini" type="text" @click="editMp(scope.row, scope.$index)">编辑</el-button>
            <el-button
              size="mini"
              type="text"
              v-if="
                today < dayjs(scope.row.agreementStartTime) ||
                (!scope.row.agreementStartTime && !scope.row.agreementEndTime)
              "
              @click="deleteMp(scope.row, scope.$index)"
            >
              删除
            </el-button>
          </template>
        </TableList>
      </div>
    </div>
    <el-dialog :visible.sync="open" width="70%" :before-close="cancel" append-to-body>
      <div slot="title" class="dialog-title">
        <span class="tit">
          {{ openTitle }}-
          <span class="u-prim-text">监测项目</span>
        </span>
      </div>
      <div class="u-df-st cursor tabs-box" style="position: relative">
        <div
          class="jcxx-tabs u-sec-text u-df-ct"
          :class="activeName === 'jcxx' ? 'jcxx-ActiveTabs' : ''"
          @click="activeName = 'jcxx'"
        >
          基础信息
        </div>
        <div
          class="htxx-tabs u-sec-text u-df-ct"
          :class="activeName === 'htxx' ? 'htxx-ActiveTabs' : ''"
          @click="activeName = 'htxx'"
        >
          合同信息
        </div>
      </div>
      <div class="xx-box">
        <MonitorInfo
          v-show="activeName === 'jcxx'"
          :enterpriseCode="queryParams.enterpriseCode"
          @selectReport="selectReport"
          :cancel="!open"
          :mpbiDisabled="mpbiDisabled"
          :open="open"
          :openTitle="openTitle"
          :mpbiProjectCode="mpbiProjectCode"
        />
        <MonitorContract
          v-if="activeName === 'htxx'"
          :enterpriseCode="queryParams.enterpriseCode"
          :cancel="!open"
          :mpciDisabled="mpciDisabled"
          :projectCode="mpbiProjectCode"
          :mpciSubmit="mpciSubmit"
          :openTitle="openTitle"
          @mpciUpload="mpciUpload"
          :mpciBuildingCode="mpciBuildingCode"
        />
      </div>

      <div slot="footer" class="dialog-footer" :class="openTitle === '详情' ? 'show-save' : ''">
        <el-button size="small" @click="cancel" type="primary" plain>取 消</el-button>
        <el-button type="primary" size="small" @click="submitForm()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
@import url(./css/index.scss);
.jcxx-tabs {
  width: 142px;
  height: 40px;
  background: url('../../assets/images/tgxm_jcxx.png') center/100% no-repeat;
  padding-left: -10px;
}
.jcxx-ActiveTabs {
  background: url('../../assets/images/tgxm_jcxx02.png') center/100% no-repeat;
}
.htxx-tabs {
  position: absolute;
  top: 0;
  left: 112px;
  width: 172px;
  height: 40px;
  background: url('../../assets/images/tgxm_htxx02.png') center/100% no-repeat;
}
.htxx-ActiveTabs {
  background: url('../../assets/images/tgxm_htxx.png') center/100% no-repeat;
}
.app-light .tabs-box {
  border-bottom: 1px solid #dcdfe6;
}
.app-dark .tabs-box {
  border-bottom: 1px solid #262f48;
}
.xx-box {
  overflow-y: auto;
  max-height: 580px;
}
.show-save {
  display: none;
}
</style>
